from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from sirogi.letter.models import Letter
from sirogi.users.models import SirogiUser
from sirogi.documents.models import Document
from sirogi.states.models import State
import datetime
from django.template import RequestContext
#import copy

#############################################################################
def index(request):
    fecha = datetime.datetime.now()
    return render_to_response('documents/index.html', RequestContext(request))

#############################################################################
def write(request):
    fecha = datetime.datetime.now()
    return render_to_response('documents/write_document.html', {'fecha': fecha}, RequestContext(request))

#############################################################################
def save(request):
	
    try:
	doc = Document()
	#st  = State()
	#import pdb;pdb.set_trace()
	us = request.user # asumo que el usuario existe por ahora
	if us.is_SirogiEditor() or us.is_SirogiManager():
	    #user = get_object_or_404(SirogiUser, username='mati')
	    #user = SirogiUser.objects.filter(username='pepe')
	    doc.owner  = us
	    doc.numDoc	= request.POST['number']
	    doc.visto = request.POST['visto']
	    doc.considerando = request.POST['consider']
	    doc.resuelve = request.POST['resolv']
	    doc.date = datetime.datetime.now()
	    doc.state = get_object_or_404(State, Name='R')
	    #doc.path  = request.POST['path']
	    #import pdb; pdb.set_trace()
	    doc.save()
	    return render_to_response('documents/write_document.html', {'ret':True}, RequestContext(request))
	
	else:
	    return render_to_response('documents/auth_document.html', RequestContext(request))
    except:
	return render_to_response('documents/auth_document.html', RequestContext(request))

#############################################################################
def edit(request, docNum):
	
	num = 0
	fecha = 0 
	titulo = 0
	visto = 0
	consider = 0
	resolv = 0
	path = 0
	
	ret = False
	owner = '0'
	date  = '0'
	stTxt = '0'
	
	try:
		doc = Document.objects.get(numDoc = docNum)
	except:
		return render_to_response('documents/invalid_document.html', RequestContext(request))
	
	cancelSt = get_object_or_404(State, Name='C')
	
	if doc.state != cancelSt:
		try:
			if docNum != '':
				#doc = Document.objects.get(numDoc = docNum)
				if doc:
					num = docNum
					visto = doc.Get_visto()
					consider = doc.Get_considerando()
					resolv = doc.Get_resuelv()
					path  = doc.Get_Path()
					#date  = datetime.datetime.now()
					date = doc.Get_date()
					st = doc.state
					stTxt = st.Desc
		except:
			result = None
	else:
		return render_to_response('documents/canceled_document.html', RequestContext(request))
		
	return render_to_response('documents/edit_document.html', {'ret': ret, 'num': num, 'date': date, 'visto': visto, 'st': stTxt, 'consider': consider, 'resolv': resolv, 'path': path, 'fecha': fecha, }, RequestContext(request))

#############################################################################
def save2(request, docNum):

	cancelSt = get_object_or_404(State, Name='C')
	try:
		doc = Document.objects.get(numDoc = docNum)
	except:
		return render_to_response('documents/invalid_document.html', RequestContext(request))
	
	us = request.user
	
	if doc.state != cancelSt:
		if us == doc.owner:
			#doc.owner  = us
			#doc.anexos = '' #request.POST['anexos']
			#doc.numDoc      = request.POST['num'] # Forbiden to change doc number
			doc.date        = request.POST['date']
			doc.considerando = request.POST['consider']
			doc.visto = request.POST['visto']
			#doc.titulo = request.POST['titulo']
			doc.resuelve = request.POST['resolv']
			doc.date = datetime.datetime.now() #request.POST['date']
			#doc.path  = request.POST['path']
	
			doc.save()
			return render_to_response('documents/edit_document.html', {'ret':True}, RequestContext(request))
		else:
			return render_to_response('documents/auth_document.html', RequestContext(request))
	else:
		return render_to_response('documents/canceled_document.html', RequestContext(request))

#############################################################################
def search(request):

	result = []
	is_owner = False
	found = False
	owner = '0'
	date  = '0'
	docNum = 0
	ret = False
	try:
		if request.POST.has_key('search_doc'):
			docNum = request.POST['search_doc']
			if docNum != '':
				doc = Document.objects.get(numDoc = docNum)
				if doc:
					result.append(docNum)
					owner	= doc.Get_Owner()
					result.append(owner)
					date	= doc.Get_date()
					result.append(date)
					found	= True
				else:
					found = False
			else:
				docNum = 0
				found = False
		
		is_manager = True
		
		if request.user == owner:
		    is_owner = True

		#try:
			#is_manager = request.user.is_SirogiManager()
		#except:
			#is_manager = False
	
		#import pdb; pdb.set_trace()
	except:
		found  = False
		result = None
		ret = True
	
	#import pdb; pdb.set_trace()
	return render_to_response('documents/index.html', {'ret': ret, 'result': result, 'is_owner': is_owner, 'found': found, 'docNum': docNum, 'owner': owner, 'date': date}, RequestContext(request))

#############################################################################
def listDocs(request):

    # Listo los docs en redaccion ('R')
    #import pdb; pdb.set_trace()
    d1 = Document.objects.filter(state__Name = 'R')
    d2 = Document.objects.filter(state__Name = 'C')
    docs = d1|d2
    
    return render_to_response('documents/list_docs.html', {'docs':docs}, RequestContext(request))

#############################################################################
def listEdit(request):

    # Listo los docs en redaccion ('R')
    #import pdb; pdb.set_trace()
    d1 = Document.objects.filter(state__Name = 'R')
    d2 = Document.objects.filter(state__Name = 'C')
    docs = d1|d2
    
    return render_to_response('documents/list_docs.html', {'docs':docs}, RequestContext(request))

#############################################################################
def addColab(request, numDoc):

    doc = Document.objects.get(numDoc = numDoc)
    
    try:
		request.POST['adding_colabs']
		adding = True
    except:
		adding = False

    if adding:
        doc.colaborators.clear()
        # XXX: ESTO DE ABAJO ES DEMASIADO FEO, HA QUE CAMBIARLO URGENTE
        # NO LO HAGO AHORA PORQUE SO LAS 5 AM Y YA NI VEO, PERO LO QE NECESITO
        # ES OBTENER LOS COLABORADORES QE SE ENVIAN POR POST DESDE
        # EL FORMULARIO
        try:
            for i in request.POST.lists()[1][1]:
                doc.colaborators.add(SirogiUser.objects.get(username = i))
                
            doc.save()
        except:
            pass    

    users = SirogiUser.objects.all()
    selected = doc.colaborators.all() 
    
    results = []
    for i in users:
    	if i in selected:
    		results.append((i.username, True))
    	else:
    		results.append((i.username, False))
    return render_to_response('documents/add_colabs.html', {'doc':doc, 'results':results}, RequestContext(request))

#############################################################################
def listApprovedView(request):

    d1 = Document.objects.filter(state__Name = 'A')
    
    return render_to_response('documents/list_approved_view_docs.html', {'docs':d1}, RequestContext(request))

#############################################################################
def viewIt(request, docNum):
	
	num = 0
	fecha = 0 
	titulo = 0
	visto = 0
	consider = 0
	resolv = 0
	path = 0
	
	ret = False
	owner = '0'
	date  = '0'
	stTxt = '0'
	
	try:
	    if docNum != '':
		doc = Document.objects.get(numDoc = docNum)
		if doc:
		    num = docNum
		    visto = doc.Get_visto()
		    consider = doc.Get_considerando()
		    resolv = doc.Get_resuelv()
		    path = doc.Get_Path()
		    date = doc.Get_date()
		    st = doc.state
		    stTxt = st.Name
	except:
	    ret = True
		
	return render_to_response('documents/view_document.html', {'ret': ret, 'd': doc, 'st': stTxt}, RequestContext(request))
	#return render_to_response('documents/view_document.html', {'ret': ret, 'num': num, 'date': date, 'visto': visto, 'titulo': titulo, 'consider': consider, 'resolv': resolv, 'path': path, 'fecha': fecha, })
	
#############################################################################	
def send_to_rev(request, id_doc):
	doc = '0'
	state = '0'
	stTxt = '0'
	cancelSt = get_object_or_404(State, Name='C')
	
	try:
		doc = get_object_or_404(Document, numDoc = id_doc)
		if doc.state != cancelSt:
			doc.state = get_object_or_404(State, Name='E')
			state = get_object_or_404(State, Name='E')
			stTxt = state.Desc
			doc.save()
		else:
			return render_to_response('documents/canceled_document.html', RequestContext(request))
	except:
		result = True

	return render_to_response('documents/view_document.html', {'d': doc, 'st': stTxt}, RequestContext(request))
